package acs.basehttp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import static io.netty.buffer.Unpooled.copiedBuffer;
public class HttpServerHandler extends
        SimpleChannelInboundHandler<FullHttpRequest> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
		Channel channel = ctx.channel();
		ByteBuf byteBuf = copiedBuffer(req.uri().getBytes());
		FullHttpResponse response = responseOK(HttpResponseStatus.OK, byteBuf);
		channel.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}


	private FullHttpResponse responseOK(HttpResponseStatus status, ByteBuf content) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
		if (content != null) {
			response.headers().set("Content-Type", "text/plain;charset=UTF-8");
			response.headers().set("Content_Length", response.content().readableBytes());
		}
		return response;
	}




}